﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Data;
using DevExpress.Utils;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Grid;

namespace QuanLyKho.BanHang
{
    public partial class DanhSachSanPham : UserControl
    {
        public DanhSachSanPham()
        {
            InitializeComponent();
            SetPropertiesGrid();
            SetPropertiesColumns();
            LoadData();
        }
        public void LoadData()
        {
            var tuNgay_gvSanPham = dtTuNgay_gvSanPham.Checked ? dtTuNgay_gvSanPham.Value.ToString("MM/dd/yyyy") : DateTime.Now.Month + "/01/" + DateTime.Now.Year;
            var denNgay_gvSanPham = dtDenNgay_gvSanPham.Checked ? dtDenNgay_gvSanPham.Value.ToString("MM/dd/yyyy") : DateTime.Now.Month + "/"
                + DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month) + "/" + DateTime.Now.Year;
            gridSanPham.DataSource = DataAll.SelectAll("SanPhamTrongCuaHang LEFT JOIN [dbo].[SanPhamHoanThien] ON [SanPhamTrongCuaHang].IDSpHoanThien = [SanPhamHoanThien].ID"
                , "[SanPhamTrongCuaHang].SoLuong AS'SoLuongChia',SanPhamTrongCuaHang.IDSpHoanThien AS'ID1',SanPhamTrongCuaHang.ID AS'IDTCH',*"
                , " WHERE (TenCuaHang =N'" + luCuaHang.Text + "' OR N'" + luCuaHang.Text + "'=N'Tất cả cửa hàng') AND (CONVERT(DATE, SanPhamTrongCuaHang.NgayChia, 0) >= CONVERT(DATE,'"
                + tuNgay_gvSanPham + "', 0) AND CONVERT(DATE, SanPhamTrongCuaHang.NgayChia, 0) <= CONVERT(DATE,'" + denNgay_gvSanPham + "' , 0))");
        }

        public void SetPropertiesGrid()
        {
            gvSanPham.BestFitColumns();
            gvSanPham.FocusRectStyle = DrawFocusRectStyle.RowFullFocus;
            gvSanPham.OptionsSelection.EnableAppearanceFocusedCell = false;
            gvSanPham.OptionsSelection.MultiSelect = true;
            gvSanPham.OptionsView.ShowGroupPanel = false;
            gvSanPham.OptionsView.ColumnAutoWidth = false;
            gvSanPham.OptionsView.ShowFooter = true;
            gvSanPham.OptionsFind.AlwaysVisible = true;
            //gvSanPham.OptionsBehavior.Editable = false;
            gvSanPham.Columns["ID1"].Visible = false;
            gvSanPham.Columns["IDTCH"].Visible = false;
            for (int i = 2; i < gvSanPham.Columns.Count; i++)
            {
                gvSanPham.Columns[i].OptionsColumn.AllowEdit = false;
            }
        }

        public void SetPropertiesColumns()
        {
            DataTable dataCuaHang = new DataTable();
            dataCuaHang.Columns.Add("TenCuaHang");
            dataCuaHang = DataAll.SelectAll("[SanPhamTrongCuaHang]", "TenCuaHang", " GROUP BY TenCuaHang");
            DataRow tatca = dataCuaHang.NewRow();
            tatca[0] = "Tất cả cửa hàng";
            dataCuaHang.Rows.InsertAt(tatca, 0);
            luCuaHang.Properties.DataSource = dataCuaHang;
            luCuaHang.Properties.Columns.Add(new LookUpColumnInfo("TenCuaHang"));
            luCuaHang.Properties.DisplayMember = "TenCuaHang";
            luCuaHang.Properties.ValueMember = "TenCuaHang";
            luCuaHang.Properties.NullText = "Tất cả cửa hàng";
            luCuaHang.Properties.ShowHeader = false;
            //luCuaHang.Properties.Columns.Add(new LookUpColumnInfo("TenCuaHang", "Tất cả cửa hàng", 20));

            gcXoa.Width = 40;
            gcSize.OptionsColumn.AllowEdit = false;

            gcSoLuong.DisplayFormat.FormatType = FormatType.Numeric;
            gcSoLuong.DisplayFormat.FormatString = "{0:0,0}";
        }

        private void luCuaHang_Leave(object sender, EventArgs e)
        {
            LoadData();

        }

        public void ExportText(string filepath)
        {
            var data = (DataView)gvSanPham.DataSource;
            string sfile = "none";
            StreamWriter str = File.AppendText(filepath + "/" + sfile + ".txt");// File.AppendText(filesave);
            for (int i = 0; i < data.Count; i++)
            {
                if (!string.IsNullOrEmpty(data[i]["TenCuaHang"].ToString()) && data[i]["TenCuaHang"].ToString() != sfile)
                {
                    str.Close();
                    sfile = data[i]["TenCuaHang"].ToString();
                    str = File.AppendText(filepath + "/" + data[i]["TenCuaHang"] + ".txt");
                }
                if (!string.IsNullOrEmpty(data[i]["MaHang"].ToString()))
                {
                    str.WriteLine(data[i]["MaHang"].ToString() + data[i]["DuoiHang"] + "," + data[i]["SoLuong"]);
                }
            }
            str.Close();
            MessageBox.Show("Export file txt thành công!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void txtText_Click(object sender, EventArgs e)
        {
            var saveFile = new FolderBrowserDialog();
            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                ExportText(saveFile.SelectedPath);
            }
        }

        private void dtTuNgay_gvSanPham_Leave(object sender, EventArgs e)
        {
            LoadData();
        }

        private void dtDenNgay_gvSanPham_Leave(object sender, EventArgs e)
        {
            LoadData();
        }

        private void bntXoa_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            if (gvSanPham.RowCount > 0)
            {
                var soluongcu = DataAll.SelectAll("SanPhamHoanThien", "SoLuong", " WHERE ID =" + gvSanPham.GetRowCellValue(gvSanPham.FocusedRowHandle, "ID1"));
                int soluongmoi = Convert.ToInt32(soluongcu.Rows[0]["SoLuong"].ToString()) +
                                 Convert.ToInt32(gvSanPham.GetRowCellValue(gvSanPham.FocusedRowHandle, "SoLuongChia"));
                string message = DataAll.Update("SanPhamHoanThien", " SoLuong=" + soluongmoi +
                    " WHERE ID =" + gvSanPham.GetRowCellValue(gvSanPham.FocusedRowHandle, "ID1"));
                if (message.Equals("success"))
                {
                    message = DataAll.Delete("SanPhamTrongCuaHang", " IDSpHoanThien=" + gvSanPham.GetRowCellValue(gvSanPham.FocusedRowHandle, "ID1"));
                }
                MessageBox.Show(message.Equals("success") ? "Xóa thành công" : message, "Message",
                                                MessageBoxButtons.OK,
                                                message.Equals("success") ? MessageBoxIcon.Information : MessageBoxIcon.Error);
                LoadData();
            }
        }

        private void gvSanPham_DoubleClick(object sender, EventArgs e)
        {
            if (gvSanPham.FocusedRowHandle >= 0)
            {
                ChiTietSanPham.MaID = gvSanPham.GetDataRow(gvSanPham.FocusedRowHandle)["ID1"].ToString();
                var themsp = new ChiTietSanPham();
                themsp.ShowDialog();
                LoadData();
                ChiTietSanPham.MaID = "0";
            }
        }
    }
}
